package org.budo.support.javax.servlet.http.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lmw
 */
public class CookieBuilder {
    private String name;

    private String value;

    private Boolean httpOnly;

    private String path;

    private Integer maxAge;

    public CookieBuilder() {}

    public CookieBuilder(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public CookieBuilder setHttpOnly(Boolean httpOnly) {
        this.httpOnly = httpOnly;
        return this;
    }

    public CookieBuilder withMaxAgeDays(Integer days) {
        return this.withMaxAge(days * 24 * 60 * 60);
    }

    public CookieBuilder withMaxAge(Integer maxAgeSeconds) {
        this.maxAge = maxAgeSeconds;
        return this;
    }

    public Cookie toCookie() {
        Cookie cookie = new Cookie(name, value);

        if (null != maxAge) {
            cookie.setMaxAge(maxAge);
        }

        if (null != httpOnly) {
            cookie.setHttpOnly(httpOnly);
        }
        if (null != path) {
            cookie.setPath(path);
        }
        return cookie;
    }

    public CookieBuilder setPath(String path) {
        this.path = path;
        return this;
    }

    public void setToResponse(HttpServletResponse response) {
        response.addCookie(this.toCookie());
    }
}
